import {Spin} from 'antd';
import styles from './EditCanvas.module.scss'
import useGetComponentInfo from "../../../hooks/useGetComponentInfo";
import {changeSelectId, ComponentsInfoType, moveComponent} from "../../../store/componentsReducer";
import {getComponentConfByType} from "../../../components/QuestionComponents";
import {useDispatch} from "react-redux";
import classNames from "classnames";
import {MouseEvent} from "react";
import useBindCanvasKeyPress from "../../../hooks/useBindCanvasKeyPress";
import {SortableContainer} from "../../../components/DargSortable/SortableContainer";
import {SortableItem} from "../../../components/DargSortable/SortableItem";

type PropsType = {
    loading: boolean
}

function genComponent(componentInfo: ComponentsInfoType) {
    const {type, props} = componentInfo
    const componentConf = getComponentConfByType(type)
    if (componentConf == null) return null
    const {Component} = componentConf
    return <Component {...props} />
}

export const EditCanvas = (props: PropsType) => {
    const {loading} = props
    const {componentList, selectedId} = useGetComponentInfo()
    const dispatch = useDispatch()

    function handleClick(event: MouseEvent, id: string) {
        event.stopPropagation()
        dispatch(changeSelectId(id))
    }

    useBindCanvasKeyPress()

    if (loading) {
        return (
            <div style={{textAlign: 'center', marginTop: '24px'}}>
                <Spin></Spin>
            </div>
        )
    }
    const componentListWithId = componentList.map(c => ({...c, id: c.fe_id}))

    function handleDragEnd(oldIndex: number, newIndex: number) {
        dispatch(moveComponent({oldIndex, newIndex}))
    }

    return (
        <SortableContainer items={componentListWithId} onDragEnd={handleDragEnd}>
            <div className={styles.canvas}>
                {componentList.filter(c => !c.isHidden).map(c => {
                    const {fe_id, isLocked} = c;
                    const wrapperDefaultClassName = styles['component-wrapper'];
                    const selectClassName = styles.selected;
                    const lockedClassName = styles.locked;
                    const wrapperClassName = classNames({
                        [wrapperDefaultClassName]: true,
                        [selectClassName]: selectedId === fe_id,
                        [lockedClassName]: isLocked
                    })
                    return (
                        <SortableItem key={fe_id} id={fe_id}>
                            <div className={wrapperClassName} onClick={e => handleClick(e, fe_id)}>
                                <div className={styles.component}>
                                    {genComponent(c)}
                                </div>
                            </div>
                        </SortableItem>
                    )
                })}
            </div>
        </SortableContainer>

    );
};